<?php

namespace app\admin\model\spell;

use app\admin\model\goods\Goods;
use app\admin\model\goods\GoodsSkuDetail;
use app\admin\model\order\Order;
use app\admin\model\order\Spelldetail;
use app\admin\model\User;
use fast\Utils;
use think\Db;
use think\Exception;
use think\Model;


class Spell extends Model
{





    // 表名
    protected $name = 'spell';

    // 自动写入时间戳字段
    protected $autoWriteTimestamp = 'int';

    // 定义时间戳字段名
    protected $createTime = 'createtime';
    protected $updateTime = false;
    protected $deleteTime = false;

    // 追加属性
    protected $append = [
        'finishTime_text'
    ];






    public function getFinishtimeTextAttr($value, $data)
    {
        $value = $value ? $value : (isset($data['finishTime']) ? $data['finishTime'] : '');
        return is_numeric($value) ? date("Y-m-d H:i:s", $value) : $value;
    }

    protected function setFinishtimeAttr($value)
    {
        return $value === '' ? null : ($value && !is_numeric($value) ? strtotime($value) : $value);
    }
    /**
     * 状态
     */
    public static function getFinishInfo()
    {
        return [
            0=>'拼团中',
            1=>'已成团',
        ];
    }
    /**
     * 开始拼团信息
     */
    public static function startSpell($orderInfo)
    {
        $joinInfo = [];
        if($orderInfo['ptid']>0){
            $joinInfo = self::where('ptid',$orderInfo['ptid'])->where('start',1)->find();
            if($joinInfo['isFinished'] == 1){
                \app\admin\model\SpellOrder::where('id',$orderInfo['id'])->update([
                    "ptid"=>0,
                    "fromUid"=>0,
                ]);
                $joinInfo = [];
                $orderInfo['ptid'] = 0;

            }

            $percent=\think\config::get("site.RobotRebatePercent");
            \app\admin\model\rebate\Rebate::saveRebateInfo([
                "uid" => $joinInfo['uid'],
                "disUid" => $orderInfo['uid'],
                "orderId" => $orderInfo['orderId'],
                "oid" => $joinInfo['orderId'],
                "type" => 13,
                "percent" => $percent,
                "price" => bcmul($orderInfo['payPrice'],$percent*0.01,2),
                "info" => '团队收益',
            ]);
        }
        //自己支付生成团记录
        $spellInfo = array(
            "ptid"=>$orderInfo['id'],
            "start"=>1,
            "uid"=>$orderInfo['uid'],
            "mobile"=>substr($orderInfo['mobile'], 0,3)."****".substr($orderInfo['mobile'], 7,4),
            "avatar"=>$orderInfo['avatar'],
            "orderId"=>$orderInfo['orderId'],
            "fromUid"=>$orderInfo['fromUid'],
            "price"=>$orderInfo['payPrice'],
            "totalPrice"=>self::getTotalPrice($orderInfo['payPrice']),
            "createtime"=>time(),
            "updatetime"=>time()
        );
        $spellInfo["balance"] = bcsub($spellInfo['totalPrice'],$spellInfo['price'],2);
//        if(!empty($joinInfo)){
//            $spellInfo["balance"] = bcsub($spellInfo['balance'],$joinInfo['price'],2);
//        }
        self::insert($spellInfo);
        //成团发送拼团短信
        \app\common\library\Sms::otherSend([
            "uid"=>$orderInfo['uid'],
            "type"=>6,
            "orderId"=>$orderInfo['orderId'],
            "chaPrice"=>$spellInfo['totalPrice'],
            "countPrice"=>$spellInfo["balance"],
        ]);
        if(!empty($joinInfo)){
            $isFinished = 0;
            $joinBalance = bcsub($joinInfo['balance'],$spellInfo['price'],2);
            if($joinBalance<=0){
                $joinBalance = 0;
                $isFinished = 1;
                \app\admin\model\SpellOrder::where('id',$orderInfo['ptid'])->where('orderStatus',2)->update([
                    "orderStatus"=>3,
                    "pttime"=>time(),
                ]);
                //解除锁定
                \app\admin\model\user\Spell::where(['ptid'=>$joinInfo['ptid'],'status'=>1])->update([
                        "status"=>9,
                        "info"=>'参团成功系统取消'
                    ]);
            }
            $re = self::where('id',$joinInfo['id'])->where('lock_version',$joinInfo['lock_version'])->update([
                "lock_version"=>$joinInfo['lock_version']+1,
                "balance"=>$joinBalance,
                "isFinished"=>$isFinished,
                "finishTime"=>$isFinished == 1?time():0,
                "updatetime"=>time(),
            ]);
            if($re == false){
                throw new Exception("参团失败");
            }
            //自己支付的团中包含参加的团信息
//            $joinSpellInfo = array(
//                "ptid"=>$orderInfo['id'],
//                "uid"=>$joinInfo['uid'],
//                "mobile"=>$joinInfo['mobile'],
//                "avatar"=>$joinInfo['avatar'],
//                "orderId"=>$joinInfo['orderId'],
//                "price"=>$joinInfo['price'],
//                "robot"=>1,
//                "createtime"=>time(),
//                "updatetime"=>time()
//            );
//            self::insert($joinSpellInfo);
            //给参加的团增加拼团记录
            $spellInfo['uid'] = $spellInfo['uid'];
            $spellInfo['ptid'] = $joinInfo['ptid'];
            $spellInfo['start'] = $spellInfo['balance'] = $spellInfo['totalPrice'] = 0;
            self::insert($spellInfo);
        }
        if($orderInfo['ptid']>0 && $orderInfo['fromUid']>0){
            \app\admin\model\user\Spell::updateSuccess($orderInfo);
        }
    }
    /**
     * 计算拼团总价
     */
    public static function getTotalPrice($price)
    {
        $bei = \think\config::get("site.pinggoodscountbei");
//        $machinbei = \think\config::get("site.pinggoodsmachinebei");
//        if(!empty($joinInfo)){
//            return bcadd(bcadd(bcmul($price,$bei,2),bcmul($price,($machinbei-1),2),2),$joinInfo['price'],2);
//        }else{
//            return bcadd(bcmul($price,$bei,2),bcmul($price,$machinbei,2),2);
//        }

        return bcmul($price,$bei,2);
    }
    /**
     * 机器人定时
     */
    public static function crontab()
    {
        $time=strtotime('-1 day');
        $list = self::where('start',1)->where('robot',0)->where('isFinished',0)->where('createtime','>=',$time)->select();
        if(empty($list)){
            return true;
        }
        $robotList = \app\admin\model\spell\Robot::where('status',1)->order('ptnum asc')->field('id,mobile,avatar,ptnum')->limit(100)->select();
        //$robotNum = \think\config::get("site.pinggoodsmachinebei");
        foreach ($list as $ks=>$vs){
            $nums = 1;
//            $robotInfo = self::where('ptid',$vs['ptid'])->where('start',0)->where('robot',1)->find();
                //第二个下单
                if($vs['createtime']>time()-rand(5,10)*60){
                    continue;
                }
                $robot = 1;

//            else{
//                //第一个下单
//                if($vs['createtime']>time()-rand(5,10)*60){
//                    continue;
//                }
//                $robot = 0;
//            }

            $rand = array_rand($robotList);
            $robotid=$robotList[$rand]['id'];
            $rOrderId=$vs['orderId'].$robotid;
            $goods=self::getRobotGoods($vs['orderId'],$vs['price'],0,$rOrderId);
            $balance = bcsub($vs['balance'],$goods['price'],2);
            if ($balance <= 0) {
                $balance = 0;
                //拼团成功修改订单状态
                \app\admin\model\SpellOrder::where('id',$vs['ptid'])->where('orderStatus',2)->update([
                    "orderStatus"=>3,
                    "pttime"=>time(),
                ]);
                //解除锁定
                \app\admin\model\user\Spell::where(['ptid'=>$vs['ptid'],'status'=>1])->update([
                    "status"=>9,
                    "info"=>'参团成功系统取消'
                ]);
                //团长拼团成功
                $joinInfo = self::where('ptid',$vs['ptid'])->where('start',1)->where('isFinished',0)->find();
                self::where('id',$joinInfo['id'])->update([
                    "lock_version"=>$joinInfo['lock_version']+1,
                    "isFinished"=>1,
                    "finishTime"=>time(),
                    "updatetime"=>time(),
                ]);
            }
            $re = self::where('id',$vs['id'])->where('lock_version',$vs['lock_version'])->update([
                "lock_version"=>$vs['lock_version']+1,
                //"balance"=>$balance>=0?$balance:0,
                "balance"=>$balance,
                "updatetime"=>time(),
                "robot"=>$robot,
            ]);
            if($re == false){
                continue;
            }
            $data= array(
                "ptid"=>$vs['ptid'],
                "uid"=>$robotList[$rand]['id'],
                "mobile"=>$robotList[$rand]['mobile'],
                "avatar"=>$robotList[$rand]['avatar'],
                "orderId"=>$rOrderId,
                "robot"=>1,
                "price"=>$goods['price'],
                "createtime"=>time(),
                "updatetime"=>time()
            );
            self::insert($data);
            \think\Db::query("UPDATE `pt_robot_user` set ptnum=ptnum+1 WHERE id=".$robotid);
        }
        return true;
    }

    private static function getRobotGoods($orderId,$price,$rid=0,$rOrderId){
        $orderInfo=Order::where(['orderId'=>$orderId])->find();
        $price=bcdiv(10,$orderInfo['discount']*0.01,2);
        $price2=bcdiv(15,$orderInfo['discount']*0.01,2);
        $arr=['asc','desc'];
        shuffle($arr);
        $skuinfo=Goods::where('price','between',[80,160])->field('goodsid,title,price,image')->limit(100)->order('mtime '.$arr[0])->select();
        $flag=0;
        if(empty($skuinfo)) {
            $flag=1;
            $skuinfo= Spelldetail::all(['orderId'=>$orderId]);
            foreach ($skuinfo as &$r){
                $r['goodsid']=$r['goodsId'];
                $r['title']=$r['goodsName'];
                $r['price']=bcmul($price,0.8,2);
            }
        }
        shuffle($skuinfo);
        $skuinfo=$skuinfo[0];
        $sku=GoodsSkuDetail::get(['goodsId'=>$skuinfo['goodsid'],'price'=>$skuinfo['price']]);
//        $price=$flag==1?$price:bcmul($skuinfo['price'],$orderInfo['discount']*0.01,2);
        $price=self::randomFloat(20,25);
        $goods=[
            'orderId'=>$rOrderId,
            'uid' =>$rid,
            'goodsId'=>$skuinfo['goodsid'],
            'skuId'=>empty($sku)?'0':$sku['skuId'],
            'goodsName'=>$skuinfo['title'],
            'skuName'=>empty($sku)?'':$sku['title'],
            'image'=>$skuinfo['image'],
            'price'=>$price,
            'quantity'=>$flag==1?$skuinfo['quantity']:1,
            'robot'  =>1
        ];
        Spelldetail::insert($goods);
        $percent=\think\config::get("site.RobotRebatePercent");
        $r=\app\admin\model\rebate\Rebate::saveRebateInfo([
            "uid" => $orderInfo['uid'],
            "disUid" => $rid,
            "orderId" => $rOrderId,
            "oid" => $orderId,
            "type" => 12,
            "percent" => $percent,
            "price" => bcmul($price,$percent*0.01,2),
            "info" => '团队收益',
        ]);
        $user=User::get(['id'=>$orderInfo['uid']]);
        $qrcodeUrl = 'http://pt-img.sdgjjy.com/share/pinGroup.html?'."&ptid=".$orderInfo['id']."&inviteCode=".base64_encode($user['invite_code']);
        $qrcodeUrl = Utils::getShortUrl($qrcodeUrl);
        \app\common\library\Sms::otherSend([
            "uid"=>$orderInfo['uid'],
            "type"=>8,
            "level"=>rand(1,3),
            "price"=> bcmul($price,$percent*0.01,2),
            "url"=>""
        ]);
        return $goods;

    }

    private  static  function randomFloat($min = 0, $max = 1)
    {
        $num = $min + mt_rand() / mt_getrandmax() * ($max - $min);
        return sprintf("%.2f", $num);
    }

}
